#include <QDebug>
#include <QXmlParseException>
#include <QTextCodec>

#include "xmlparser.h"
#include "rsschannel.h"
#include "xmlcommon.h"
//
static QString channel = "channel";
XmlParser::XmlParser() 
					: QObject(), QXmlDefaultHandler()
{
	init();
}

XmlParser::~XmlParser()
{
}

void XmlParser::init()
{
	_channel << "channel" 
			 << "feed" ;
	_item << "item" 
			<< "entry";

	_import << "description" 
			<< "link" 
			<< "title" 
			<< "pubDate"
			<< "content"
			<< "published"
			<< "uri"
			<< "updated";
}

bool XmlParser::startDocument ()
{
	//TODO:document stard here, do we have to do smth ?
	//m_cod = QTextCodec::codecForName("ISO 8859-2");
	//QTextCodec::setCodecForCStrings(m_cod);

	qDebug() << "start document";
	m_channel = new RssChannel( );
	m_leaf = NULL;
	return true;
}

bool XmlParser::startElement ( const QString & namespaceURI, const QString & localName, const QString & qName,
								 const QXmlAttributes & atts )
{
	if( _channel.contains( qName ) )
	{
		if( qName == "channel" )
			m_channel->setType( _eChannel );
		else
			m_channel->setType( _eFeed );

		m_leaf = m_channel;
		m_leaf->setName(qName);
	}
	else if( _item.contains( qName ))
	{
		m_leaf = new RssLeaf();
		m_leaf->setName(qName);
	}
	m_data.clear();
	return true;
}

bool XmlParser::characters( const QString &chars )
{
	m_data += chars;
	return true;
}

bool XmlParser::endElement ( const QString & namespaceURI, const QString & localName, const QString & qName )
{
	if( m_leaf )
	{
		if( _item.contains( qName ))
		{
			m_channel->addItem( *m_leaf );
		}
		else if ( qName == "image" )
		{
			//todo: add image to the other table if it has to b stored
		}
		//else if( qName != "channel" && qName != "rss" )//&& qName != "item" && qName != "image" )
		else if( _import.contains( qName ))
		{
			if( !m_data.isEmpty() )
				m_leaf->addData( qName, m_data );
		}
	}
	return true;
}

bool XmlParser::endDocument()
{
	emit(documentEnd( m_channel ));
	return true;
}

bool XmlParser::fatalError( const QXmlParseException &exception )
{
	qDebug() << "Fatar xml error occurred:" << exception.message();
	return true;
}
//eof
